# -*- coding: utf-8 -*-
from pagemagic.utils.goodtext.utils import bulkreplace
import re
import rules

def process_text(s):
    if not s.strip():
        return s
    s = u' %s ' % s
    s = bulkreplace(s, rules.all)
    return s.strip()

_protect_html_rules = (
    re.compile('''<pre[^>]*>.*?</pre>''', re.S|re.I),
    re.compile('''<style[^>]*>.*?</style>''', re.S|re.I),
    re.compile('''<script[^>]*>.*?</script>''', re.S|re.I),
    re.compile('''<!--.*?-->''', re.S|re.I),
    re.compile('''<[^>]*[\s"'][^>]*>'''),  # tags with spaces or quotes inside
)

def process_html(s):
    p = TextBlockProtector()
    s = p.protect(s, _protect_html_rules)
    s = process_text(s)
    s = p.unprotect(s)
    return s

class TextBlockProtector:
    def __init__(self):
        self._storage = {}

    def protect(self, s, regexlist):
        self._storage = {}
        for regex in regexlist:
            s = regex.sub(self._add, s)
        return s

    def unprotect(self, s):
        for k, v in self._storage.items():
            s = s.replace(k, v, 1)
        return s

    def _add(self, matchobj):
        k = '<tag%d>' % len(self._storage)
        self._storage[k] = matchobj.group(0)
        return k
